package model.environment;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.jdom.JDOMException;

import model.Sale;
import model.XML;

public class Sales {
	
	//private static HashMap<Integer, Integer> mapOfSales = new HashMap<Integer, Integer>();
	private static List<Sale> sales = null;
	private static ReentrantLock itemLock = new ReentrantLock();
	private static long lastUpdate = new Date().getTime();
	
	
	/**
	 * Returns a list of all sales made from this shop. 
	 * @return a complete list of sales from this shop.
	 */
	public static List<Sale> getShopSales() {	
		try {
			itemLock.lock();
			
			long timeSinceLastUpdate = new Date().getTime() - lastUpdate;
			
			if (sales == null || timeSinceLastUpdate > StaticInfo.UPDATE_TIMEOUT)
			{
				try {
					sales = XML.getShopSales();
					lastUpdate = new Date().getTime();
				}
				catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} finally {
			itemLock.unlock();
		}
		return sales;
	}
	
	
	/**
	 * Returns a list of all sales of an specific item.
	 * @param itemID of the item.
	 * @return sales of the item.
	 */
	public static List<Sale> getItemSales(int itemID) {
		List<Sale> itemSales = new ArrayList<Sale>();
		List<Sale> shopSales = getShopSales();
		
		for(Sale s : shopSales){
			if(s.getItemID() == itemID){
				itemSales.add(s);
			}
		}
		return itemSales;
	}
	
	
	/**
	 * Gets how many of this item has been sold. 
	 * @param itemID of the item.
	 * @return the amount of this item that has been sold. 
	 */
	public static int getNumberOfSales(int itemID) {
		List<Sale> itemSales = getItemSales(itemID);
		int number = 0;
		
		for(Sale s: itemSales){
			number += s.getSaleAmount();
		}
		return number;
	}
	
	/**
	 * Gets a list of all sales that a customer has med
	 * @param customerID of the customer.
	 * @return sales that the customer has made. 
	 */
	public static List<Sale> getCustomerSales(int customerID) {
		List<Sale> customerSales = null;
		try {
			customerSales = XML.getCustomerSales(customerID);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return customerSales;
	}
}
